package com.day.newcorp;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;

public class Main {

	private final String TIME_FORMAT = "yyyyMMddHHmmssSSSZ";

	public boolean isValid(String tokenString) {
		try {
			ValidityToken token = new ValidityToken(tokenString);
			boolean[] flags = { false, false, false };
			for (Field field : token.getFields()) {
				if (field.getPosition() == 0) {
					flags[0] = true;
				} else if (field.getPosition() == 1) {
					flags[1] = true;
				} else if (field.getPosition() == 2) {
					flags[2] = true;
				}
			}
			for (boolean flag : flags) {
				if (flag == false)
					return false;
			}
		} catch (Exception e) {
			return false;
		}

		return true;
	}

	public boolean isExpired(String tokenString) {
		ValidityToken token;
		try {
			token = new ValidityToken(tokenString);
			for (Field field : token.getFields()) {
				if (field.getPosition() == 1) {
					Date timeStamp = new SimpleDateFormat(TIME_FORMAT)
							.parse(field.getValue());
					return new Date().getTime() - timeStamp.getTime() > 900000;
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return true;
		}
	}

	public String createNewToken(String UUID) {
		ValidityToken token = new ValidityToken();
		token.addField(new Field(0, "UUID", UUID));
		token.addField(new Field(1, "TIMESTAMP", new SimpleDateFormat(
				TIME_FORMAT).format(new Date())));
		token.addField(new Field(2, "EXPIRY DATE", new SimpleDateFormat(
				TIME_FORMAT).format(new Date(new Date().getTime() + 900000))));
		return token.getTokenString();

	}

	public static void main(String[] args) throws InvalidKeyException,
			NoSuchAlgorithmException, NoSuchProviderException,
			NoSuchPaddingException, ShortBufferException,
			IllegalBlockSizeException, BadPaddingException {
		String Token = new Main().createNewToken("123456789");
		byte[] encrypted = Encryptor.encrypt(Token.getBytes());
		System.out.println(new Main().isValid(new String(Encryptor
				.decrypt(encrypted))));

	}
}
